<template>
  <a-spin :spinning="loadingFile">
    <base-breadcrumb>
      <a-card>
        <title-name title="项目信息" />
        <a-form-model
          ref="form1"
          layout="horizontal"
          :model="form"
          :rules="rules"
        >
          <a-row :gutter="24">
            <a-col
              :md="16"
              :sm="16"
            >
              <a-form-model-item
                label="所属单位"
                prop="projectId"
                :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
                :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"
              >
                <org-tree-select
                  v-model="form.projectId"
                  is-auto-select-first
                  is-need-auth
                  check-strictly
                  @select="selectOrg"
                  @getProjectInfo="getProjectInfo"
                />
              </a-form-model-item>
            </a-col>
            <!--          <a-col-->
            <!--            :md="8"-->
            <!--            :sm="8"-->
            <!--          >-->
            <!--            <a-form-model-item-->
            <!--              label="分公司"-->
            <!--              :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"-->
            <!--              :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"-->
            <!--              prop="branchCompanyId"-->
            <!--            >-->
            <!--              <SelectSubCompany-->
            <!--                v-model="form.branchCompanyId"-->
            <!--                placeholder="请选择"-->
            <!--                @change="clearData"-->
            <!--              />-->
            <!--            </a-form-model-item>-->
            <!--          </a-col>-->
            <!--          <a-col-->
            <!--            :md="8"-->
            <!--            :sm="8"-->
            <!--          >-->
            <!--            <a-form-model-item-->
            <!--              label="项目名称"-->
            <!--              :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"-->
            <!--              :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"-->
            <!--              prop="projectId"-->
            <!--            >-->
            <!--              <SelectProject-->
            <!--                v-model="form.projectId"-->
            <!--                placeholder="请选择"-->
            <!--                :form="form"-->
            <!--                :is-clear="true"-->
            <!--                key-value="branchCompanyId"-->
            <!--                @change="getManagerNameReq"-->
            <!--                @projectNum="projectNums"-->
            <!--              />-->
            <!--            </a-form-model-item>-->
            <!--          </a-col>-->
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="项目编号"
                :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
                :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"
              >
                <BaseInput
                  v-model="form.projectNum"
                  placeholder=""
                  disabled
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="项目经理"
                :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
                :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"
                prop="projectManagerId"
              >
                <a-select
                  v-model="form.projectManagerId"
                  allow-clear
                  placeholder="请选择"
                  @change="getScore"
                >
                  <a-select-option
                    v-for="item in projectMangers"
                    :key="item.id"
                    :value="item.id"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="扣分前剩余分数"
                :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
                :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"
              >
                <a-input-number
                  v-model="form.remainingPointsBeforeDeduction"
                  disabled
                  :min="0"
                  :max="9999999999999"
                  :step="1"
                  :precision="2"
                />
                <!-- <BaseInput v-model="form.remainingPointsBeforeDeduction" disabled /> -->
              </a-form-model-item>
            </a-col>
          </a-row>

          <title-name title="扣分信息" />
          <a-row :gutter="24">
            <a-col
              :md="24"
              :sm="24"
              class="points-info"
            >
              <a-form-model-item
                label="处罚认定"
                class="pointReason"
                :label-col="{ lg: { span: 2 }, sm: { span: 2 } }"
                :wrapper-col="{ lg: { span: 22 }, sm: { span: 22 } }"
                prop="pointDeductionReasonId"
              >
                <a-select
                  v-model="form.pointDeductionReasonId"
                  placeholder="请选择"
                  style="width: 100%"
                  @change="getPointsScore"
                >
                  <a-select-option
                    v-for="item in pointDeductions"
                    :key="item.id"
                    :value="item.id"
                    :disabled="item.statusCode === -1"
                    :class="item.statusCode === -1 ? 'hideoption' : ''"
                  >
                    {{ item.deductScoreCondition }}
                  </a-select-option>
                </a-select>
                <!-- <a-tree-select
                v-model="form.pointDeductionReasonId"
                placeholder="请选择"
                style="width: 100%"
                :tree-data="pointDeductions"
                @change="getPointsScore"
              /> -->
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col
              :md="24"
              :sm="24"
            >
              <a-form-model-item
                label="风险底线事件"
                :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
                :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"
                prop="remark"
              >
                <BaseTextarea
                  v-model="form.remark"
                  placeholder="请输入风险底线事件"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col
              :md="8"
              :sm="8"
              class="requiredFormItem"
            >
              <a-form-model-item
                label="扣分分数"
                prop="pointsScore"
                :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
                :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"
              >
                <a-input-number
                  v-model="form.pointsScore"
                  :min="0"
                  :max="9999999999999"
                  :step="1"
                  placeholder="请输入"
                  :precision="2"
                />
                <!-- <BaseInput
                v-model="form.pointsScore"
                placeholder=""
                disabled
              /> -->
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="创建人"
                :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
                :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"
              >
                <BaseInput
                  v-model="form.creatorName"
                  placeholder=""
                  disabled
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="创建时间"
                :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
                :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"
              >
                <BaseInput
                  v-model="form.createTime"
                  disabled
                />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>

        <title-name title="证明资料上传" />
        <a-upload
          name="file"
          :show-upload-list="false"
          :multiple="true"
          :before-upload="beforeUpload"
          :disabled="spinning"
          @change="handleChanges"
        >
          <a-button
            type="primary"
            style="margin-bottom: 20px"
          >
            <a-icon
              :type="spinning ? 'loading': 'upload'"
              style="font-size: 1.2rem"
            />上传
          </a-button>
        </a-upload>
        <a-button
          type=""
          :disabled="selectedRows.length == 0"
          style="margin-bottom: 20px; margin-left: 20px"
          @click="deleteExteriorFile()"
        >
          <a-icon style="font-size: 1.2rem" />删除
        </a-button>

        <a-table
          row-key="commonId"
          bordered
          :columns="columnAssment"
          :data-source="dataAssement"
          :row-selection="rowSelections"
        >
          <span
            slot="serial"
            slot-scope="text, record, index"
          >{{ index + 1 }}</span><span
            slot="action"
            slot-scope="text, record, index"
          >
            <a
              :href="'/api/ycloud-file-center/oper/download?access_token=' + token + '&fileId=' + record.fileId"
              target="_parent"
            >导出</a>
            <a-divider type="vertical" />
            <a
              href="javascript:"
              @click="$filePreview(record)"
            >预览</a>
          </span>
        </a-table>
      </a-card>

      <div
        style="float: right"
        class="page-btn-right-top"
      >
        <a-button
          type="primary"
          class="ml12"
          :loading="loadingDraft"
          @click="saveDraft"
        >
          保存草稿
        </a-button>
        <a-button
          type="primary"
          :loading="loading"
          class="ml12"
          @click="submit"
        >
          提交
        </a-button>
        <a-button
          type="primary"
          class="ml12"
          @click="goBack"
        >
          关闭
        </a-button>
      </div>
      <!-- 选择审批人 -->
      <selectApprover
        :business-id="businessId"
        :process-config="setProcessConfig"
      />
      <!-- 选择审批人 -->
    </base-breadcrumb>
  </a-spin>
</template>

<script>
import Vue from 'vue'
import { addPointsRecord, editPointsRecord, getPointsRecordDetails, getManagerName, pointsDeduction, pointsRecordFileQuery, pointsRecordFileDelete, pointsRecordFileUpload } from '@/api/project/pointsRecord'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/SelectProjects/SelectProject' // 项目
import { uploadFile, deleteUploadFile } from '@/api'
import ARow from 'ant-design-vue/es/grid/Row'
import debounce from 'lodash/debounce'

const columnAssment = [
  {
    title: '序号',
    width: 65,
    dataIndex: 'serial',

    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '附件名称',
    dataIndex: 'fileName'
  },
  {
    title: '附件格式',
    dataIndex: 'suffixName',
    width: '25%'
  },
  {
    title: '操作',
    key: 'action',
    width: '20%',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'a' + Date.now(),
  components: {
    ARow,
    SelectSubCompany,
    SelectProject
  },
  data() {
    return {
      loading: false,
      loadingDraft: false,
      loadingFile: false,
      projectMangers: [],
      managersQuery: {
        branchCompanyId: '',
        projectId: ''
      },
      businessCode: 'PM27', // 附件编码
      dataAssement: [], // 附件上传
      uploadFiles: {},
      deleteObj: {},
      token: '',
      fileFileds: null,
      fileIds: [],

      columnAssment,

      changeForm: [], // 变更形式
      pointDeductionReasonId: [], // 变更原因
      changeType: [], // 变更类型
      profession: [], // 专业
      proposer: [], // 提出方
      projectIds: [], // 提出方

      projects: [], // 分公司下的项目

      value: [],
      value2: [],
      // 一次最多上传
      num: 10,
      // 最大数量
      count: 100,
      // 文件列表
      files: [],
      // 上传中
      spinning: false,

      form: {
        projectManagerId: undefined,
        projectId: undefined,
        remainingPointsBeforeDeduction: '',
        creatorName: JSON.parse(sessionStorage.getItem('ycloud-user_info')).name,
        createTime: this.getNowDate()
      },

      id: '',
      projectNames: [],

      selectedRowKeys: [],
      selectedRows: [],
      pointDeductions: [],

      contractAmount: '', // 自有施工合同额

      rules: {
        branchCompanyId: [{ required: true, message: '请选择分公司', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择项目', trigger: 'blur' }],
        projectManagerId: [{ required: true, message: '请输入选择项目经理', trigger: 'change' }],
        pointsScore: [{ required: true, message: '请输入', trigger: 'change' }],
        pointDeductionReasonId: [{ required: true, message: '请输入选择扣分情况', trigger: 'change' }],
        remark: [{ required: true, message: '请输入处罚认定信息', trigger: 'blur' }]
      },
      isInit: false,
      // 流程配置
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      // 业务id
      businessId: null
    }
  },

  async created() {
    this.id = this.$route.query.id

    this.token = Vue.getAcloudProvider().getAccessToken()

    this.pointsDeductionReq()
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('project_manager_risk_three')
  },
  computed: {
    rowSelections() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        selectedRows: this.selectedRows, // 当前行所有数据
        onChange: this.onSelectChanges
      }
    }
  },
  methods: {
    selectOrg(val) {
      
      if (val && val.length) {
        this.form.projectId = val[val.length - 1].projectId
        this.form.branchCompanyId = val[val.length - 2].orgId
        this.$refs.form1.clearValidate(['projectId'])
        // this.getAuditProjectList()
      }
      // if (this.isInit) {
        this.getManagerNameReq()
      // }
    },
    getProjectInfo(val) {
      this.form.projectNum = val.projectNum
      console.log(val)
    },
    clearData() {
      this.form.projectId = ''
      this.form.projectNum = ''
      this.form.projectManagerId = undefined
      this.form.remainingPointsBeforeDeduction = ''
    },
    //  获取扣分情况分数
    getPointsScore(val) {
      // let obj = this.getObjByTree(this.pointDeductions, val)
      // this.form.pointsScore = obj.pointsScore
    },
    getObjByTree(arr, val) {
      let result = null
      if (!arr) return // return; 中断执行
      for (let i in arr) {
        if (result !== null) break
        let item = arr[i]
        if (item.value === val) {
          result = item
          break
        } else if (!!item?.children?.length) {
          result = this.getObjByTree(item.children, val)
        }
      }
      return result
    },

    // 积分年份
    pointsDeductionReq() {
      let that = this
      this.isInit = true
      pointsDeduction().then((res) => {
        that.pointDeductions = [...res.data]
        if (that.id) {
          that.getPointsRecordDetailsReq()
        }
      })
    },
    deleteExteriorFile() {
      let that = this
      if (that.selectedRowKeys.length == 0) {
        that.$message.error('请先选中需要删除的附件！')
        return
      }
      if (that.id) {
        that.$confirm({
          title: '删除',
          content: '确定删除附件吗？',
          onOk() {
            // pointsRecordFileDelete({businessId:that.id,fileList:that.fileIds}).then(res=>{
            //   if(res.code == 200 || res.data.code == 200){
            //     that.$message.success("删除附件成功！")
            that.dataAssement = that.dataAssement.filter((item) => {
              return !that.fileIds.includes(item.commonId)
            })
            let arr = []
            that.dataAssement.forEach(function (obj, i) {
              arr.push(obj.commonId)
            })

            that.$message.success('删除成功！')
            that.form.fileIds = arr
            that.selectedRowKeys = []
            that.selectedRows = []

            // }
            // })
          },
          onCancel() {}
        })
      } else {
        that.$confirm({
          title: '删除',
          content: '确定删除附件吗？',
          onOk() {
            that.loadingFile = true
            deleteUploadFile({ fileIds: that.fileFileds }).then((res) => {
              if (res.code == '0' || res.data.code == '0') {
                let data = that.dataAssement
                let selectDatas = that.fileIds
                that.dataAssement = data.filter((item) => {
                  return !selectDatas.includes(item.commonId)
                })

                that.$message.success('删除成功！')
                that.loadingFile = false
                that.selectedRowKeys = []
                that.selectedRows = []
              }
              that.loadingFile = false
            })
          },
          onCancel() {}
        })
      }
    },
    onSelectChanges(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      let fileFileds = []
      let fileIds = []
      selectedRows.forEach(function (obj, i) {
        fileFileds.push(obj.fileId)
        fileIds.push(obj.commonId)
      })
      this.fileFileds = fileFileds.join(',') // 删除公共附件
      this.fileIds = fileIds // 有业务id 删除附件
    },

    beforeUpload(info) {
      return false
    },
    /**
     * @description: 文件上传防抖
     * @param {function}
     * @return {void}
     */
    fileChange: debounce(function () {
      this.handleUploadFun()
    }, 500),

    /**
     * @description: 500M提示
     * @param {void}
     * @return {function}
     */
    sizeDebounce: debounce(function () {
      this.$message.error('上传文件不可超出500M')
    }, 500),
    /**
     * @description: 附件名弹窗提示
     * @param {void}
     * @return {function}
     */
    nameDebounce: debounce(function () {
      this.$confirm({
        title: '提示',
        content: this.errorTips ? this.errorTips : '请规范附件名称，附件名称中需含有汉字',
        okType: 'danger'
      })
    }, 500),
    /**
     * @description: 接管文件上传
     * @param {object} info 文件对象
     * @return {void}
     */
    handleChanges(info) {
      let pass = true
      const { file } = info
      if (file.size / 1024 / 1024 > 500) {
        // 附件大小校验
        // 限制文件大小为500M
        this.sizeDebounce()
        pass = false
      }
      if (this.needChineseName) {
        // 附件名称需要汉字校验
        let re = new RegExp('[\u4E00-\\u9FFF]+', 'g')
        if (!re.test(file.name)) {
          this.nameDebounce()
          pass = false
        }
      }
      if (pass) {
        this.files.push(file)
        this.fileChange()
      }
    },

    /**
     * @description: 判断及操作上传文件队列
     * @return {void}
     */
    async handleUploadFun() {
      console.log(this.dataAssement, this.files)
      let pass = true
      if (pass && this.dataAssement.length + this.files.length > this.count) {
        pass = false
        this.$message.error(`最多上传${this.count}个文件！`)
        this.files = this.files.slice(0, this.count - this.dataAssement.length)
      }
      if (pass && this.files.length > this.num) {
        this.$message.error(`一次最多上传${this.num}个文件！`)
        this.files = this.files.slice(0, this.num)
      }
      this.spinning = true
      // 防止上传错误一直loading
      try {
        for (let i = 0; i < this.files.length; i++) {
          await this.uploadFun(this.files[i])
        }
      } catch (err) {
        console.log(err)
      } finally {
        this.files = []
        this.spinning = false
      }
    },
    /**
     * @description: 上传函数拆分
     * @param {object} file 文件
     * @return {void}
     */
    uploadFun(file) {
      return new Promise(async (resolve, reject) => {
        const data = new FormData()
        data.append('file', file)
        data.append('businessCode', this.businessCode)
        uploadFile(data)
          .then((res) => {
            if (res.code === 200) {
              let arrys = []
              if (this.dataAssement) {
                arrys = [res.data]
                this.dataAssement = arrys.concat(this.dataAssement)
              } else {
                this.dataAssement = [res.data]
              }
              let arr = []
              this.dataAssement.forEach(function (obj, i) {
                arr.push(obj.commonId)
              })

              this.form.fileIds = arr
              this.selectedRowKeys = []
            }
            resolve()
          })
          .catch(() => {
            reject()
          })
      })
    },
    // 项目编号
    projectNums(val) {
      this.form.projectNum = val
    },

    // 关闭
    goBack() {
      this.$multiTab.close(this.$route.fullpath)
    },

    // 保存草稿
    saveDraft() {
      let that = this
      that.$refs.form1.validate((err, values) => {
        if (err) {
          that.loadingDraft = true
          if (that.id) {
            that.form.id = that.id
            if (that.form.fileInfoIds != null) {
              let arr = that.dataAssement
              // let arr = that.form.fileInfoIds.concat(that.dataAssement)
              let commonIds = []
              if (arr.length > 0) {
                arr.forEach(function (obj, i) {
                  commonIds.push(obj.commonId)
                })
              }
              let newArr = [...new Set(commonIds)]
              that.form.fileIds = newArr
            }

            editPointsRecord(that.form).then((res) => {
              if (res.data.code == 200 || res.code == 200) {
                that.$message.success('保存草稿成功！')
                that.loadingDraft = false
                that.goBack()
              }
            })
          } else {
            that.form.statusCode = 0
            addPointsRecord(this.form).then((res) => {
              if (res.data.code == 200 || res.code == 200) {
                that.$message.success('保存草稿成功！')
                that.loadingDraft = false
                that.goBack()
              }
            })
          }
        }else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
    },

    // 提交
    submit() {
      let that = this
      that.$refs.form1.validate((err, values) => {
        if (err) {
          this.submitApprovalConfirm(this.processConfig, (flag)=>{
            if(!flag) {
              this.loading = false
              return
            }
            if (that.id) {
              that.form.id = that.id
              that.form.statusCode = 1
              if (that.form.fileInfoIds != null) {
                let arr = that.dataAssement
                let commonIds = []
                if (arr.length > 0) {
                  arr.forEach(function (obj, i) {
                    commonIds.push(obj.commonId)
                  })
                }
                let newArr = [...new Set(commonIds)]
                that.form.fileIds = newArr
              }
              that.loading = true
              this.setProcessConfig = null
              editPointsRecord(that.form).then((res) => {
                if (res.data.code == 200 || res.code == 200) {
                  that.$message.success('提交成功！')
                  this.businessId = res.data.id
                  this.setProcessConfig = this.processConfig
                }
              })
              .finally(() => {
                that.loading = false
              })
            } else {
              that.loading = true
              this.setProcessConfig = null
              that.form.statusCode = 1
              addPointsRecord(that.form)
                      .then((res) => {
                        if (res.data.code == 200 || res.code == 200) {
                          that.$message.success('提交成功！')
                          this.businessId = res.data.id
                          this.setProcessConfig = this.processConfig
                        }
                      })
                      .finally(() => {
                        that.loading = false
                      })
            }
          })

        }else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
    },

    // 获取扣分记录详情
    getPointsRecordDetailsReq() {
      getPointsRecordDetails({ id: this.id }).then((res) => {
        if (res.code == 200) {
          this.form = { ...res.data }
          this.form.projectId = res.data.projectId
          this.form.projectManagerId = res.data.projectManagerId
          this.$forceUpdate()
          if (this.id) {
            this.handlerPointsUnuse()
          }
          this.dataAssement = res.data.fileInfoIds || []
        }
      })
    },

    /**
     * @description 处理详情的扣分情况
     * 详情：扣分情况 不可用-select中没有下发 手动push进来 然后select中不显示
     */
    handlerPointsUnuse() {
      const { pointDeductionReason, pointDeductionReasonId } = this.form
      const existArr = this.pointDeductions.filter((v) => v.id === pointDeductionReasonId)
      if (existArr && !existArr.length) {
        const clonearr = JSON.parse(JSON.stringify(this.pointDeductions))
        this.pointDeductions.push({
          id: pointDeductionReasonId,
          deductScoreCondition: pointDeductionReason,
          statusCode: -1
        })
      }
    },

    // 获取项目经理
    getManagerNameReq() {
      if (!this.isInit) {
        this.form.projectManagerId = ''
      }
      this.managersQuery.branchCompanyId = this.form.branchCompanyId
      this.managersQuery.projectId = this.form.projectId

      getManagerName(this.managersQuery).then((res) => {
        this.isInit = false
        if (res.code == 200) {
          this.projectMangers = res.data
        }
      })
    },

    // 获取项目经理剩余分数
    getScore(val) {
      if (!val) {
        this.form.remainingPointsBeforeDeduction = ''
        this.form.projectManagerId = undefined
        return
      }
      const target = this.projectMangers.find((item) => item.id == val)
      this.form.remainingPointsBeforeDeduction = target.remainingPointsBeforeDeduction
    }
  }
}
</script>
<style scoped>
/deep/.ant-select-tree li .ant-select-tree-node-content-wrapper.ant-select-tree-node-content-wrapper-normal {
  max-width: 1000px;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  display: inline-block;
}
/deep/ .pointReason.ant-row.ant-form-item .ant-select-tree {
  height: 300px;
  width: 100%;
}
/deep/ .pointReason .ant-select-dropdown.ant-select-dropdown-placement-bottomLeft {
  min-width: 1100px;
}
</style>
